<?php

namespace App\Http\Controllers;

use App\Events\ReplyChange;
use App\Models\Reply;
use App\Notifications\TopicReplied;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\ReplyRequest;
use Illuminate\Support\Facades\Auth;

class RepliesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

	public function store(ReplyRequest $request, Reply $reply)
	{
		$reply->content = clean($request->content, 'user_topic_body'); // 处理xss安全
		$reply->user_id = Auth::id();
		$reply->topic_id = $request->topic_id;
		$reply->save();

		# 更新帖子回复数和最后回帖的用户ID
		event(new ReplyChange($reply->topic, $reply->user_id));
        # 通知帖子作者，有回复信息
		$reply->topic->user->notify(new TopicReplied($reply));

		return redirect()->to($reply->topic->link())->with('success', '评论成功~');
	}

    /**
     * 删除评论
     *
     * @param Reply $reply
     *
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @data 2022/11/9
     * @author fanzhaogui
     */
	public function destroy(Reply $reply)
	{
		$this->authorize('destroy', $reply);
		$reply->delete();

        # 更新帖子回复数和最后回帖的用户ID
        event(new ReplyChange($reply->topic, 0));

		return redirect()->to($reply->topic->link())->with('success', '评论删除成功~');
	}


    public function edit(Reply $reply)
    {
        $this->authorize('update', $reply);
        return view('replies.create_and_edit', compact('reply'));
    }

    public function update(ReplyRequest $request, Reply $reply)
    {
        $this->authorize('update', $reply);
        $reply->update($request->all());

        return redirect()->route('replies.show', $reply->id)->with('success', 'Updated successfully.');
    }
}
